import os
import re
import time
from PIL import Image
import ddddocr
from DrissionPage import Chromium, ChromiumOptions


def check_(image_path):
    # 初始化ddddocr对象
    ocr = ddddocr.DdddOcr(beta=True)
    # 使用Pillow打开图片
    original_image = Image.open(image_path)

    # # 读取图片内容
    # with open(image_path, 'rb') as f:
    #     image = f.read()

    # 进行验证码识别
    result = ocr.classification(original_image)
    print(result)
    return result


def verify_code(page):
    verify_frame = page.get_frame(1)
    code = verify_frame.ele('#imgVerify')
    code_path = code.get_screenshot(os.path.join(os.getcwd(), 'img'), f'code.png')
    res = check_(code_path)
    verify_frame.ele('#yzm').input(res)
    page.ele('tag:a@@text():确定').click()


def wait_(page, str, time_out=30):
    start_time = time.time()
    while time.time() - start_time < time_out:
        if page.ele('#index').text.strip() == str:
            return True
        time.sleep(0.5)
    raise TimeoutError('等待超时')


def get_info(page):
    li_list = page.s_eles('css:#categorypagingcontent > ul > .ewb-list-node')
    for li in li_list:
        detail_url = li.ele('tag:a').attr('href')
        title = li.ele('tag:a').text
        date = li.ele('.ewb-list-date').text
        data = {
            'url': detail_url,
            'title': title,
            'date': date
        }
        print(data)


def main():
    chrome_path = os.environ.get('chrome')
    co = ChromiumOptions()
    co.set_paths(browser_path=chrome_path)
    co.set_timeouts(base=30)
    co.set_argument('--start-maximized')
    co.set_argument('--disable-blink-features=AutomationControlled')
    browser = Chromium(co)

    page = browser.latest_tab
    page.get('https://www.sxggzyjy.cn/jydt/001001/001001001/subPage_jyxx.html')
    page.ele('xpath://span[text()="工程建设项目招标投标"]')
    total_page = int(re.search(r'\d+/(\d+)', page.ele('#index').text).group(1))
    print(f'共计页数{total_page}')
    for i in range(1, total_page + 1):
        if i == 1:
            get_info(page)
        else:
            page.ele('#target').input(i)
            time.sleep(0.5)
            page.ele('tag:a@@text():GO').click()
            if i < 6:
                pass
            else:
                verify_code(page)
            wait_(page, f'{i}/{total_page}')
            get_info(page)
        time.sleep(1)
    print(2)


if __name__ == '__main__':
    print(check_(r'D:\PycharmProjects\pythonProject\spider_reverse\全国资源交易平台（陕西）DrissionPage\img\1.png'))



